extern "C" {
  #include <stdlib.h>
}

#include "WProgram.h"
#include "RGBMessage.h"

char number[4]= {0,0,0,0};

RGBMessageReceiver::RGBMessageReceiver ( const Handler messageHandler ) 
{
    next=0;   
    handler=messageHandler;
}

void RGBMessageReceiver::accept(byte newchar) 
{
    if (newchar == '\\')
    {
        next=0;
        return;
    }
    
    message[next++]=newchar;

    message[MESSAGE_SIZE-1]='\0';
    
    if (ready()) {
        
        
        handler(*this);
        next=0;
    }
    
}

int RGBMessageReceiver::toNumber(int pos) const
{
    number[0]=message[pos];
    number[1]=message[pos+1];
    number[2]=message[pos+2];
    return atoi(number);
}

void RGBMessageReceiver::rgb(int rgb[3]) const
{
    
    rgb[0]= toNumber(RPOS);
    rgb[1]= toNumber(GPOS);
    rgb[2]= toNumber(BPOS);
}

char RGBMessageReceiver::status() const
{
    return message[STATUSPOS];
}

byte RGBMessageReceiver::led() const
{
    return message[LEDPOS]-'0';   
}

boolean RGBMessageReceiver::ready() const
{
    return next== (MESSAGE_SIZE-1);
}
    
const char* RGBMessageReceiver::text() const 
{
    return message;
}